package com.fwtai.service;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**无返回值,使用阿里巴巴推荐的创建线程池的方式处理业务,线程安全-推荐的*/
public final class TaskAsync{

  //私有构造方法
  private TaskAsync(){}

  public static TaskAsync getInstance(){
    return Singleton.INSTANCE.getInstance();
  }

  private enum Singleton{
    INSTANCE;
    private final TaskAsync singleton;
    //JVM保证这个方法绝对只调用一次
    Singleton(){
      singleton = new TaskAsync();
    }
    public TaskAsync getInstance(){
      return singleton;
    }
  }

  //无返回值,用法:TaskAsync.getInstance().execute(()-> {});
  public void execute(final Runnable command){
    //todo 使用阿里巴巴推荐的创建线程池的方式,通过ThreadPoolExecutor构造函数自定义参数创建,参考 https://blog.csdn.net/wildwolf_001/article/details/117874802 https://baijiahao.baidu.com/s?id=1702681736898954397
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(
      Runtime.getRuntime().availableProcessors()*32,76800,1L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(51200),new ThreadPoolExecutor.CallerRunsPolicy()
    );
    try {
      executor.execute(command);
    } catch (final Exception exception){
      exception.printStackTrace();
    }finally{
      executor.shutdown();//释放线程池
    }
  }
}